package nl.hanze.designpatterns.mvc.controller;

import java.awt.event.ActionEvent;

import nl.hanze.designpatterns.domain.LoginCredential;
import nl.hanze.designpatterns.mvc.model.MainModel;
import nl.hanze.designpatterns.mvc.view.LoginGui;
import nl.hanze.designpatterns.mvc.view.MainAppGui;


public class LoginController extends Controller {
	
	private LoginGui view;
	private MainModel model;
	
	public LoginController(LoginGui loginGui){
		init(loginGui);
	}
	
	private void init(LoginGui loginGui){
		this.view = loginGui;
		this.model = loginGui.getModel();
		
	}
	
	public void handleLoginRequest(String username, char[] password){
		if(!username.equals("") && password.length > 0){
				LoginCredential loginCredential = new LoginCredential(username, this.decodePasswordField(password));
				if(model.getLoginModel().isValid(loginCredential)){
					System.out.println("userid: " + loginCredential.getUserId());
					System.out.println("username: " + username);
					System.out.println("password: " + this.decodePasswordField(password));
					this.loginSucces(loginCredential);
			}			
		}
		
	}
	
	private String decodePasswordField(char[] password){
		String passwordDec = "";
		for(int i = 0; i < password.length; i++ ){
			passwordDec  += password[i];
		}
		return passwordDec;
	}
	
	private void loginSucces(LoginCredential loginCredential){
		this.view.setVisible(false);
		this.view.dispose();
		new MainAppGui(model);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
	
	}
}
